import { useState, useRef, useEffect } from 'react';
import { ChatOpenAI } from "@langchain/openai";
import { BufferMemory } from "langchain/memory";
import { ConversationChain } from "langchain/chains"; // “ConversationChain”具有一种简单的记忆类型，它会记住所有先前的输入/输出并将其添加到传递的上下文中

// 您希望它记住先前的消息，以便可以利用上下文进行更好的交流。
// 这将是一种 "短期记忆"。在更复杂的情况下，您可以想象一个链/代理随着时间的推移记住关键信息 - 这将是一种 "长期记忆" 形式。
export default function Memory() {
  const [messages, setMessages] = useState<Array<{role: string, content: string}>>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const chatContainerRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [messages]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const chatModel = new ChatOpenAI({
        modelName: "gpt-3.5-turbo",
        configuration: {
          apiKey: 'xxx', // Replace with your OpenAI API key
          baseURL: 'https://xxx' // Replace with your OpenAI API endpoint 代理地址
        },
      });
      const memory = new BufferMemory(); // 创建一个BufferMemory实例
      const chain = new ConversationChain({ llm: chatModel, memory: memory }); // 将BufferMemory实例传递给ConversationChain

      const newMessages = [...messages, {role: 'user', content: input}];
      setMessages(newMessages);
      setInput('');
      
      const { response } = await chain.call({ input: newMessages.map(m => m.content).join('\n') });
      setMessages([...newMessages, {role: 'assistant', content: response}]);
      
      setLoading(false);
    } catch (error) {
      console.error(error);
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: '800px', margin: '0 auto', fontFamily: 'Arial, sans-serif' }}>
      <h2 style={{ color: '#333', textAlign: 'center' }}>记忆链</h2>
      <div style={{
        height: '500px',
        overflow: 'auto',
        border: '1px solid #e0e0e0',
        borderRadius: '8px',
        backgroundColor: '#f9f9f9',
        boxShadow: 'inset 0 1px 3px rgba(0,0,0,0.1)'
      }}>
        <div ref={chatContainerRef} style={{ height: '500px', overflow: 'auto', padding: '10px' }}>
          {messages.map((msg, i) => (
            <div 
              key={i} 
              style={{
                margin: '10px 0',
                display: 'flex',
                flexDirection: msg.role === 'user' ? 'row-reverse' : 'row',
              }}
            >
              <div 
                style={{
                  maxWidth: '70%',
                  padding: '10px 15px',
                  borderRadius: '18px',
                  backgroundColor: msg.role === 'user' ? '#dcf8c6' : '#ffffff',
                  border: '1px solid #e0e0e0',
                  boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
                }}
              >
                <strong style={{ color: msg.role === 'user' ? '#075e54' : '#333' }}>
                  {msg.role === 'user' ? '我' : 'AI'}:
                </strong> 
                <div style={{ wordBreak: 'break-word' }}>{msg.content}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <form onSubmit={handleSubmit} style={{ marginTop: '20px', display: 'flex' }}>
        <input 
          type="text" 
          value={input} 
          onChange={(e) => setInput(e.target.value)} 
          disabled={loading}
          style={{
            flex: 1,
            padding: '12px',
            borderRadius: '24px',
            border: '1px solid #e0e0e0',
            outline: 'none',
            fontSize: '16px',
            boxShadow: '0 1px 2px rgba(0,0,0,0.1)'
          }}
          placeholder="请输入"
        />
        <button 
          type="submit" 
          disabled={loading} 
          style={{
            padding: '12px 24px',
            marginLeft: '10px',
            borderRadius: '24px',
            backgroundColor: '#075e54',
            color: 'white',
            border: 'none',
            cursor: 'pointer',
            fontSize: '16px',
            transition: 'background-color 0.3s'
          }}
          onMouseEnter={(e) => {
            if (!loading) {
              (e.target as HTMLButtonElement).style.backgroundColor = '#054a42';
            }
          }}
          onMouseLeave={(e) => {
            if (!loading) {
              (e.target as HTMLButtonElement).style.backgroundColor = '#075e54';
            }
          }}
        >
          {loading ? 'Sending...' : 'Send'}
        </button>
      </form>
    </div>
  );
}
